package servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.BankCustomer;
import exception.UnknownCustomerException;
import factory.DaoFactory;


/**
 * Servlet implementation class BalanceServlet
 */
@WebServlet("/Balance")
public class BalanceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BalanceServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id = request.getParameter("id");

		if (id != null) {
			float balance = 0;
			String address = null;
			try {
				balance = DaoFactory.getBalanceDao().find(id);
				BankCustomer customer = new BankCustomer(id, balance);
				if (customer.getBalance() < 0) {
					request.setAttribute("badCustomer", customer);
					address ="/balance/NegativeBalance.jsp";
				} else if (customer.getBalance() - 10000 > 0) {
					request.setAttribute("goodCustomer", customer);
					address ="/balance/HighBalance.jsp";
				} else {
					request.setAttribute("normalCustomer", customer);
					address ="/balance/NormalBalance.jsp";
				}
			} catch (UnknownCustomerException e) {
				// TODO Auto-generated catch block
				request.setAttribute("id", id);
				address ="/customer/UnknownCustomer.jsp";
			} finally {
				RequestDispatcher dispatcher =request.getRequestDispatcher(address);
				dispatcher.forward(request, response);
			}
		} else {
			response.sendRedirect(request.getContextPath() + "/Login");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
